<template>
	<view>
		<u-navbar @leftClick="leftClick" bgColor="#ffffff" :placeholder="true" :title="title"></u-navbar>

		<view class="wrap">
			<u--form :model="form" ref="uForm" class="from" :error-type="errorType">
				<view class="required">
					<view class="title">必填信息</view>
					<view class="required-box">
						<u-form-item label="场地名称" labelWidth="80" prop="storeName" required>
							<u-input v-model="form.storeName" type="text" inputAlign="right"
								placeholder="例如:广州万达店(字数不可超过12个)" :maxlength="12" border="none" clearable />
						</u-form-item>
						<u-form-item label="所在地区" labelWidth="80" @click.stop="openPicker" prop="region" required>
							<u-input v-model="form.region" type="digit" inputAlign="right" placeholder="省市区县乡镇等"
								:maxlength="12" border="none" clearable :disabled="true" disabledColor="#ffffff" />
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
						<u-form-item label="详细地址" labelWidth="80" prop="address" required>
							<u-input v-model="form.address" type="text" inputAlign="right" placeholder="街道门牌号等"
								:maxlength="20" border="none" clearable>
								<template slot="suffix">
									<view class="location" @click="locationSelect">
										<u-icon name="map-fill" color="#6072FF" size="24"></u-icon>
										<view>定位</view>
									</view>
								</template>
							</u-input>
						</u-form-item>

						<u-form-item required label="客服电话" labelWidth="80" prop="serviceMobilePhone">
							<u-input v-model="form.serviceMobilePhone" type="number" inputAlign="right"
								placeholder="请输入客服电话" :maxlength="11" border="none" clearable />
						</u-form-item>
					</view>
				</view>
				<view class="other-information">
					<view class="title">其他信息</view>
					<u-form-item label="微信/支付宝费率" labelWidth="130" v-if="form.merchantId">
						<u-input readonly v-model="form.feeValue" type="digit" inputAlign="right" placeholder="0.6"
							:maxlength="20" border="none" clearable />
						<view class="u-m-l-10" slot="right">%</view>
					</u-form-item>
					<u-form-item label="收款商户" labelWidth="80"
						@click="navMerchant('/pages-merchant/list/list?fromPage=')">
						<u--input v-model="form.merchantId" border="none" type="number" placeholder="请选择收款商户"
							inputAlign="right" clearable :disabled="true" disabledColor="#fff" />
						<u-icon slot="right" name="arrow-right" />
					</u-form-item>
					<u-form-item v-if="showSalesman" label="业务员ID" labelWidth="130">
						<u-input v-model="form.salesmanId" type="text" inputAlign="right" placeholder="请输入业务员ID"
							:maxlength="50" border="none" clearable />
					</u-form-item>
					<u-form-item v-if="showSalesman" label="AppID" labelWidth="130">
						<u-input v-model="form.navWeChatAppId" type="text" inputAlign="right" placeholder="请输入AppID"
							:maxlength="50" border="none" clearable />
					</u-form-item>
					<view class="m-flex-row u-row-between store-defult">
						<view>
							<view>设置默认场地</view>
							<view class="tip">每次注册会默认推荐使用该场地</view>
						</view>
						<view>
							<u-switch v-model="form.defaultStatus" @change="change" activeColor="#6072FF"></u-switch>
						</view>
					</view>
					<u-collapse :border="false">
						<u-collapse-item title="自动退款/投币,获取用户授权信息">
							<u-form-item label="自动退款" labelWidth="130">
								<view class="u-flex-row u-row-between">
									<u-icon name="question-circle" @click="automaticRefundTips = true"></u-icon>
									<u-switch v-model="form.automaticRefund" asyncChange @change="automaticRefundChange"
										activeColor="#6072FF"></u-switch>
								</view>
							</u-form-item>
							<u-form-item label="获取用户授权信息" labelWidth="130">
								<view class="u-flex-row u-row-between">
									<view></view>
									<u-switch v-model="form.fillInMemberInfo" @change="fillInMemberInfoChange"
										activeColor="#6072FF"></u-switch>
								</view>
								<text
									class="u-font-24 u-m-t-20">开启后，发起支付时提示用户、授权信息包括用户头像、昵称，手机号等，整个系统只需要授权一次(用户拒绝后仍可正常发起支付)。</text>
								<!--                <text class="u-font-24 u-m-t-20">开启后，需要用户授权后才能发起支付、授权信息包括用户头像、昵称，手机号等，整个系统只需要授权一次。</text>-->
							</u-form-item>
						</u-collapse-item>
					</u-collapse>
				</view>
			</u--form>
			<view class="add-view">
				<u-button text="保存" @click="save()" :customStyle="saveCustomStyle"></u-button>
			</view>
		</view>
		<lotus-address v-on:choseVal="choseValue" :lotusAddressData="lotusAddressData"></lotus-address>
		<site-type :siteTypeShow="siteTypeShow" @siteTypeColse="siteTypeColse" @siteChange="siteChange"></site-type>

		<u-popup :show="automaticRefundTips" mode="center" @close="automaticRefundClose" round="20rpx"
			:customStyle="{width: '600rpx'}">
			<view class="u-p-l-30 u-p-r-30 u-p-t-50 u-p-b-50 u-font-28">
				<view class="">
					<view class="u-m-t-10 u-m-b-10">1、会员购币出币不成功将自动退款。</view>
					<view class="u-m-t-10 u-m-b-10">2、充电桩类启动充电不成功将自动退款。</view>
					<view class="u-m-t-10 u-m-b-10">3、喷泉类启动不成功将自动退款。</view>
				</view>
				<view class="u-flex-row u-row-around u-m-t-50" v-if="automaticRefundSwitch">
					<u-button type="default" :plain="true" :hairline="true" text="不开启" :customStyle="cancelCustomStyle"
						@click="automaticRefundTipsCancel()"></u-button>
					<u-button type="primary" :plain="true" :hairline="true" text="开启" :customStyle="confirmCustomStyle"
						@click="automaticRefundTipsConfirm()"></u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import lotusAddress from "@/components/Winglau14-lotusAddress/Winglau14-lotusAddress.vue";
	export default {
		components: {
			lotusAddress
		},
		data() {
			return {
				title: '修改投放场地',
				value: null,
				lotusAddressData: {
					visible: false,
					provinceName: '',
					cityName: '',
					townName: '',
				},
				putInACoin: '开启、关闭为批量处理，如需单台设备独立设置请到“设备管理—>某场地—>某设备 自动投币”',
				region: '',
				form: {
					id: 0,
					storeName: '',
					province: '',
					city: '',
					district: '',
					region: '',
					address: '',
					longitude: '', // 经度
					latitude: '', // 维度
					merchantId: '',
					feeValue: '',
					defaultStatus: false,
					// 自动退款
					automaticRefund: false,
					// 自动投币
					automaticCoin: false,
					fillInMemberInfo: false,
					// 抖音费率, 输入范围：0-50，两位小数
					tiktokRate: '',
					// 美团费率, 输入范围：0-50，两位小数
					meiTuanRate: '',
					//客服电话
					serviceMobilePhone: '',
					//啊小专属业务员ID
					salesmanId: null,
					navWeChatAppId: '',
				},
				rules: {
					storeName: [{
							max: 18,
							message: '场地名称字符不能超过18个',
							required: true,
						},
						{
							required: true,
							message: '场地名称不能为空'
						},
					],
					region: [{
						required: true,
						message: '请选择所在地区'
					}, ],
					address: [{
						required: true,
						message: '详细地址不能为空'
					}, ],
					serviceMobilePhone: [{
						required: true,
						message: '客服电话不能为空'
					}, ],
					// merchantId: [
					// 	{
					// 		required: true,
					// 		message: '请选择收款商户'
					// 	},
					// ],
				},
				errorType: 'toast',
				siteTypeShow: false,
				// 从哪个页面来，index:从首页——>场地列表——>当前页面，deviceRegister——>设备注册页面——>场地列表——>当前页面
				from: 'index',

				automaticRefundTips: false,

				automaticRefundSwitch: false,
				fillInMemberInfoTips: false,
				cancelCustomStyle: {
					border: '1rpx solid rgb(224, 224, 224)',
					fontSize: '26rpx',
					color: 'rgb(193,191,191)',
					width: '250rpx',
				},
				confirmCustomStyle: {
					fontSize: '26rpx',
					width: '250rpx',
				},
				saveCustomStyle: {
					width: '700rpx',
					height: '88rpx',
					background: 'rgb(96,114,255)',
					borderRadius: '60rpx',
					color: '#FFF',
					fontSize: '28rpx',
				},
				params: {
					pageNum: 1,
					pageSize: 10,
					keyword: '',
					type: 1,
				},
				//是否显示业务员ID输入框 和 appID
				showSalesman: false,
			}
		},
		onLoad(option) {
			this.from = option.from;
			// console.log(this.form)
			this.form.id = option.siteId;
			this.title = option.siteId > 0 ? "修改投放场地" : "添加投放场地";
			if (option.siteId > 0) {
				this.siteLoad(option.siteId);
			}
			this.merchantListLoad();
		},
		onShow() {
			var that = this;
			uni.$on('location-select', (newData) => {
				if (newData) {
					const {
						title,
						location
					} = newData
					console.log(newData)
					this.form.address = title
					this.form.longitude = location.lng
					this.form.latitude = location.lat

					this.lotusAddressData.provinceName = newData.ad_info.province;
					this.lotusAddressData.cityName = newData.ad_info.city;
					this.lotusAddressData.townName = newData.ad_info.district;

					this.form.region =
						`${newData.ad_info.province} ${newData.ad_info.city} ${newData.ad_info.district}`; //region为已选的省市区的值
					this.form.province = newData.ad_info.province;
					this.form.city = newData.ad_info.city;
					this.form.district = newData.ad_info.district;
				}
			})
			const accountInfo = uni.getAccountInfoSync();
			if (accountInfo.miniProgram.appId === 'wx0e051e95864ef215') {
				this.showSalesman = true
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {

			// 商户变更
			merchantIdChange(data, feeValue) {
				console.log("data_feeValue", data + "_" + feeValue)
				this.$nextTick(() => {
					this.form.merchantId = data;
					this.form.feeValue = feeValue * 100;
					this.$helpers.toast('已变更收款商户，请点击下方保存');
					// console.log("this.form.merchantId", this.form.merchantId)
				})
			},

			automaticRefundTipsConfirm() {
				this.automaticRefundTips = false;
				setTimeout(() => {
					this.form.automaticRefund = true;
					this.automaticRefundSwitch = false;
					this.$helpers.toast('开启自动退款');
				}, 600);
			},

			automaticRefundTipsCancel() {
				this.automaticRefundTips = false;
				setTimeout(() => {
					this.form.automaticRefund = false;
					this.automaticRefundSwitch = false;
					this.$helpers.toast('不开启自动退款');
				}, 600);
			},

			automaticRefundClose() {
				this.automaticRefundTips = false;
			},

			automaticRefundChange(e) {
				this.automaticRefundTips = true;
				this.automaticRefundSwitch = true;
			},

			fillInMemberInfoChange() {},
			save() {
				if (this.form.tiktokRate) {
					if (isNaN(Number(this.form.tiktokRate)) || (Number(this.form.tiktokRate) > 50 || Number(this.form
							.tiktokRate) < 0)) {
						this.$helpers.toast('抖音费率输入范围：0-50');
						return;
					}
				}
				if (this.form.meiTuanRate) {
					if (isNaN(Number(this.form.meiTuanRate)) || (Number(this.form.meiTuanRate) > 50 || Number(this.form
							.meiTuanRate) < 0)) {
						this.$helpers.toast('美团费率输入范围：0-50');
						return;
					}
				}
				// console.log("this.form:",this.form)
				this.$refs.uForm.validate().then(valid => {
					if (valid) {
						this.$api('merchantStore.save', this.form).then(res => {
							if (res.status == 0) {
								this.$helpers.toast(res.data);
							} else {
								getApp().err("保存不成功：" + res.msg);
								return;
							}
							try {
								//获取所有页面栈实例列表
								const pages = getCurrentPages();
								// console.info(pages)
								if (this.from == 'deviceRegister') {
									const deviceRegisterPage = pages[pages.length - 2];
									// console.log("deviceRegisterPage")
									// console.log(deviceRegisterPage)
									deviceRegisterPage.$vm.initData();
								}
							} catch (e) {
								console.error(e.toString())
							}
							// 逻辑~
							setTimeout(() => {
								if (this.from == 'deviceRegister' || this.from == 'giftExchange') {
									uni.navigateBack({
										delta: 2,
										animationType: 'pop-out',
										animationDuration: 200
									})
								} else {
									uni.navigateBack({
										delta: 1,
										animationType: 'pop-out',
										animationDuration: 200
									})
								}
							}, 1000)
						})
					}
				}).catch(errors => {})

			},
			// 返回上一页
			leftClick() {
				uni.navigateBack();
			},

			navTab(url) {
				uni.switchTab({
					url: url
				})
			},
			navMerchant(url) {
				uni.navigateTo({
					url: url + 'add-merchant-store'
				})
			},
			merchantListLoad() {
				this.$api('merchant.findMerchantListByUserId', this.params).then(res => {
					if (res.status == 0) {
						if (!uni.$u.test.isEmpty(res.data.list) && res.data.list.length == 1) {
							this.form.merchantId = res.data.list[0].merchantId;
							this.form.feeValue = res.data.list[0].feeValue * 100;
						}
					} else {
						getApp().err("请求不成功：" + res.msg);
					}
				}).catch(() => {

				});
			},
			// 接收地址选择框选的数据
			cityChange(e) {
				this.form.province = e.province.label;
				this.form.city = e.city.label
				this.form.district = e.area.label;
				this.form.region = e.province.label + ' ' + e.city.label + ' ' + e.area.label;
			},
			showSiteType() {
				this.siteTypeShow = true;
			},
			siteTypeColse(e) {
				this.siteTypeShow = e;
			},
			// 场地类型赋值
			siteChange(e) {
				if (e == "" || e == null) {
					this.$helpers.toast('请选择场地类型');
				}
				this.form.siteType = e;
				this.siteTypeShow = false;
			},
			siteLoad(id) {
				this.$api('merchantStore.findMerchantStoreByUserIdByStoreId', {
					id: id
				}).then(res => {
					if (res.data == null) {
						this.$helpers.toast('请求不成功，请重试');
						this.form = null;
					} else {
						this.form.id = res.data.id;
						this.form.storeName = res.data.storeName;
						this.form.province = res.data.province;
						this.form.city = res.data.city;
						this.form.district = res.data.district;
						this.form.region = res.data.region;
						this.form.address = res.data.address;
						this.form.merchantId = res.data.merchantId;
						this.form.defaultStatus = res.data.defaultStatus;
						this.form.automaticRefund = res.data.automaticRefund;
						this.form.automaticCoin = res.data.automaticCoin;
						this.form.fillInMemberInfo = res.data.fillInMemberInfo;
						this.form.tiktokRate = res.data.tiktokRate;
						this.form.meiTuanRate = res.data.meiTuanRate;
						this.form.salesmanId = res.data.salesmanId;
						this.form.navWeChatAppId = res.data.navWeChatAppId;
						this.form['region'] = res.data.province + ' ' + res.data.city + ' ' + res.data.district;
						this.form.serviceMobilePhone = res.data.serviceMobilePhone
					}
				})
			},

			change() {

			},
			//打开picker
			openPicker() {
				this.lotusAddressData.visible = true;
				// console.log(this.form.id)
				if (this.form.id > 0) {
					this.lotusAddressData.provinceName = this.form.province;
					this.lotusAddressData.cityName = this.form.city;
					this.lotusAddressData.townName = this.form.district;
				} else {
					if (!this.lotusAddressData.provinceName) {

						this.lotusAddressData.provinceName = '广东省';
						this.lotusAddressData.cityName = '广州市';
						this.lotusAddressData.townName = '白云区';
					}
				}

			},
			//回传已选的省市区的值
			choseValue(res) {
				//res数据源包括已选省市区与省市区code
				// console.log(res);
				this.lotusAddressData.visible = false; //visible为显示与关闭组件标识true显示false隐藏
				//res.isChose = 1省市区已选 res.isChose = 0;未选
				if (res.isChose) {
					this.lotusAddressData.provinceName = res.province; //省
					this.lotusAddressData.cityName = res.city; //市
					this.lotusAddressData.townName = res.town; //区
					this.form.region = `${res.province} ${res.city} ${res.town}`; //region为已选的省市区的值
					this.form.province = res.province;
					this.form.city = res.city;
					this.form.district = res.town;
				}
			},
			//选择地图位置
			locationSelect() {
				var that = this;
				wx.chooseLocation({
					success: function(res) {
						console.info(res);
						that.form.address = res.name;
						that.form.longitude = res.longitude; // 经度
						that.form.latitude = res.latitude; // 维度
					},
					complete(res) {
						console.info(res);
					}
				})

			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F6F6F6;
	}

	/deep/ .u-cell__body {
		padding: 20rpx 0 !important;
	}

	.other-information {
		background-color: white;
		margin-top: 30rpx;
		padding: 25rpx 40rpx 20rpx;
	}

	.title {
		font-size: 38rpx;
	}

	.required {
		background-color: white;
		padding: 50rpx 40rpx 0;

		.required-box {
			padding: 0 10rpx;
		}
	}

	/deep/.lotus-address-picker2 {
		color: #6072FF !important;
	}

	/deep/.lotus-address-picker2:after {
		border-left-color: #6072FF !important;
		border-bottom-color: #6072FF !important;
	}

	/deep/.lotus-address-action-affirm {
		color: #6072FF !important;
	}

	/deep/ .u-input__content__field-wrapper__field {
		font-size: 26rpx !important;
		color: rgba(0, 0, 0, 0.9) !important;
	}

	/deep/ .u-form-item__body__left__content__label {
		font-size: 32rpx !important;
		color: #797777 !important;
	}

	.wrap {
		color: rgba(0, 0, 0, 0.8);
		font-size: 28rpx;

		/deep/ .u-form-item {
			border-bottom: 1rpx solid rgba(0, 0, 0, 0.03);
		}

		/deep/ .u-form-item__body {
			padding: 40rpx 0 20rpx !important;
		}

		.location {
			font-size: 20rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			color: #6072FF;
		}

		.store-defult {
			margin: 50rpx 0rpx;

			.tip {
				color: rgba(0, 0, 0, 0.5);
				font-size: 26rpx;
				margin-top: 10rpx;
			}
		}

		.add-view {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			margin-top: 100rpx;
			margin-bottom: 50rpx;

			.add {
				width: 100%;
				height: 88rpx;
				background: rgb(96, 114, 255);
				border-radius: 60rpx;
				color: #FFFFFF;
				font-family: Microsoft YaHei;
				font-size: 28rpx;
				letter-spacing: 0.3;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
			}
		}
	}

	/deep/ .u-safe-area-inset-bottom {
		padding-bottom: inherit;
	}
</style>